// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
//导入路由组件，用于跳转等
import { Router, hashHistory, Link } from 'dva/router';
// 引入antd的组件
import { Tabs, Radio, Tooltip, Spin, Form, Table, Pagination, Popconfirm, Upload, Icon, message, Input, Select, Row, Col, Checkbox, Button, Modal, DatePicker, Tree} from 'antd';
// 判断对象是否为空
import { isEmpty, isArray,cloneDeep } from 'lodash'
import CollapsiblePanels from 'widget/CollapsiblePanels/CollapsiblePanels'
// 引入列表页组件
import ListPage from 'widget/PageTmpl/ListPage'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './advertisingListStyle.less'
import Uploader from "../../../widget/Upload";
// 表单域
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;
// 表单项布局
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 19 }
};
let newBannerList_default=[{
  "url": "",
  "href": "",
  "type": 1,
  "ord": '',
  "published": '0',
  "channel": 101,
  "title": '轮播图',
}]
const routeView = function ({ dispatch, model, form }) {
  // 取出model对象，命名空间
  const { modelObj, namespace, } = model;
  let { bannerList = {}, oVisible, writeUrl, nowUrlChange, pageTotal,pageInfo, pageNo, pageSize, newBanner, newBannerList=[], status ,mpUrls,mpUrlsSelectKeys,mpUrlsObj,activeKey,channelIndex} = modelObj;
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue, } = form
  console.log('modelObj',modelObj)
  newBannerList[0].channel =  channelIndex==1?'101':'201';
  
  function removeImgUrl(index) {
    console.log(index);
    bannerList[channelIndex][index].url = '';
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { bannerList }
    })
  }
  function updateImageModel(value, i) {
    bannerList[channelIndex][i].url = value;
    // 分发到model
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { bannerList }
    })
    console.log(value,i, 'updateImageModel...banner');
  };
  //新的
  function removenewImgUrl(index) {
    console.log(index);
    newBannerList[0].url = '';
    changeState({newBannerList})
  }
  function updatenewImageModel(value, i) {
    newBannerList[0].url = value;
    changeState({newBannerList})
  };
  const addImg = (type) => {
    //添加图片
    bannerList[channelIndex].push({
      "url": "",
      "href": "",
      "type": 1,
      "ord": '',
      "published": '0',
      "channel": channelIndex==1?'101':'201',
      "title": '轮播图'
    });
    changeState({ bannerList })
  };
  //链接弹窗确定按钮
  const oHandleOk = () => {
    let url=writeUrl
    validateFields(
      (err) => {
        if (!err) {
          if(activeKey==1){
            url=mpUrlsObj.currentItem.key
          }else if(activeKey==2){
            url=writeUrl
          }
          if (status == 'new') {
            newBannerList[0].href = url;
            console.log(newBannerList);
            changeState({ oVisible: false, newBannerList })
            return;
          } else {
            bannerList[channelIndex][nowUrlChange].href = url;
            console.log(bannerList);
            changeState({ oVisible: false, bannerList })
          }
        }
      },
    );
  };
  //保存修改状态
  const newBanenrOk = (payload) => {
    console.log(newBannerList);
    debugger
    if (!newBannerList[0].url.trim()) {
      message.warn('请上传广告图');
      return;
    }
    if (newBannerList[0].ord=='') {
      message.warn('请填写序号');
      return;
    }
    // if (newBannerList[0].href.length < 5) {
    //   message.error('请填写跳转链接');
    //   return;
    // }

    dispatch({ type: `${namespace}/createBannerList`, payload: { slideshowCreateReqDtos: [...newBannerList], pageNo, pageSize } });
    changeState({ newBanner: false, bannerList, })
  };

  //修改状态
  const changeState = (payload) => {
    console.log(payload);
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ...payload }
    })
  };
  //
  function changeUrl(state, i, status) {
    console.log(i);
    changeState({ ...state, nowUrlChange: i, status });
    // console.log(nowUrlChange, 'nowUrlChange', writeUrl:''});
  }
  function saveUrl(url) {
    console.log(url.target.value);
    changeState({ writeUrl: url.target.value });
  }
  function delImg(i) {
    if (bannerList[channelIndex][i].slideshowId) {
      dispatch({ type: `${namespace}/deleteBanner`, payload: { slideshowId: bannerList[channelIndex][i].slideshowId, pageNo, pageSize } });
      bannerList[channelIndex].splice(i, 1);
    }
    changeState({ bannerList });
  }
  function onChange(pageNo, pageSize) {
    pageInfo[channelIndex].pageNo=pageNo
    pageInfo[channelIndex].pageSize=pageSize
    changeState({ pageInfo });
    dispatch({ type: `${namespace}/getBannerList`, payload: { pageNo: pageNo, pageSize: pageSize } });
    console.log(pageNo, pageSize);
  }
  function saveBanner(i='') {
     if(bannerList[channelIndex][i].url == ''){
      message.warn('图片不能为空')
      return
    }
    if(!bannerList[channelIndex][i].ord){
      message.warn('请填写序号')
      return
    }
    if (bannerList[channelIndex][i].slideshowId) {
      dispatch({ type: `${namespace}/changeBanner`, payload: { ...bannerList[channelIndex][i], pageNo, pageSize } });
    }else{
    
    }
    // changeState({ bannerList });
  }
  function openNewSave() {
    newBannerList_default[0].channel =  channelIndex==1?'101':'201';
    newBannerList=cloneDeep(newBannerList_default)
    changeState({ newBanner: true, oVisible: false ,newBannerList});
  }
  function saveSort(val, i) {
    bannerList[channelIndex][i].ord = val;
    console.warn(bannerList, val, i);
    changeState({ bannerList });
  }
  function saveSortNew(val) {
    newBannerList[0].ord = val;
    changeState({ newBannerList });
  }
  
  mpUrlsObj.mpUrls = [{
    node: {
      title: '住房供应链',
      value: '0',
      key: '0',
    },
    children: [
      {
        node: {
          title: '首页',
          value: 'pages/biz/index/index',
          key: 'pages/biz/index/index',
        },
        children: null,
      },
      {
        node: {
          title: '找房',
          value: 'pages/biz/findHouse/findHouse',
          key: 'pages/biz/findHouse/findHouse',
        },
        children: null,
      },
      {
        node: {
          title: '我的',
          value: 'pages/biz/my/mine/mine',
          key: 'pages/biz/my/mine/mine',
          children: null,
        },
      }],
  }]
  //树形目录
  const loop = arr => arr.map((item) => {
    if (item.children && item.children.length > 0) {
      return (
        <TreeNode key={item.node.key + ''} title={item.node.title} itemInfo={item.node}>
          {loop(item.children)}
        </TreeNode>
      );
    }
    return <TreeNode key={item.node.key + ''} title={item.node.title} itemInfo={item.node}/>;
  });
  
  // 小程序路树展开
  function onExpand (expandedKeys) {
    console.log('onExpand', expandedKeys)
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    mpUrlsObj = {...mpUrlsObj, expandedKeys,}
    changeState({mpUrlsObj})
  }
  
  // 小程序路树选中
  function onSelect (selectedKeys, info) {
    console.log('onSelect', info)
    let currentItem=!isEmpty(info.selectedNodes)&&info.selectedNodes[0].props.itemInfo||{};
    let link=selectedKeys[0]||''
    mpUrlsObj = {...mpUrlsObj, selectedKeys,link,currentItem}
    changeState({mpUrlsObj})
  }
  return <div className="public_listMain">
    <div className="functionButton">
      <Button type="primary" htmlType="button" size="large" onClick={() => { openNewSave() }}  >新增图片</Button>
    </div>
    {/*切换tab*/}

    {/*美的置业云*/}
    <Form>
      {/*首页banner设置*/}
      <CollapsiblePanels title="轮播图">
        <div className={styles.explainText}>
          <i className="iconfont icon-ic_info_px"></i>
          <span>尺寸要求：1372x736px ，文件大小300kb以下</span>
        </div>
        
        <Tabs onChange={(channelIndex)=>{changeState({channelIndex})}} type="card" activeKey={channelIndex}>
          <TabPane tab=" 住房供应链" key="1"></TabPane>
          {/* <TabPane tab=" 智美分销" key="2"></TabPane> */}
        </Tabs>
        {channelIndex==1&&
        <Row gutter={16} className={styles.oBanners} >
          {
            bannerList['1'] && bannerList['1'].map((item, i) => {
              return <Col span={12} key={'otoBanners_' + i} className={styles.largeBanners}>
                <div className={styles.largeBanner}>
                  <div className={styles.oBannerLeft}>
                    图{i + 1}
                  </div>
                  <div className={styles.oBannerMiddle}>
                    <Uploader uploadedUrls={item.url}
                              // imgUrlSize={'146'}
                              removeFileCbf={(e) => { removeImgUrl(i) }}
                              uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl, i) }}
                              showType={'3'}
                              fileType='image'
                              fileMaxSize='0.3'
                              minCropBoxWidth={1372}
                              minCropBoxHeight={736}
                              maxFiles='1' />
                    <div>
                      <Tooltip placement="topLeft" title="链接地址：（链接请加上传输协议，如http://或https://）">
                        <div style={{ textIndent: '24px', margin: '10px 0' }}>链接地址：(链接请加上传输协议，如http://或https://)</div>
                      </Tooltip>
                      <div className={styles.oImgUrls}>
                        <p className={styles.urlCss}>
                          {item.href ? item.href : '暂无链接...'}
                        </p>
                      </div>
                      <FormItem {...formItemLayout} label="序号" required={true}>
                        {getFieldDecorator(`ord${i}`, {
                          initialValue: item.ord,
                          normalize: (e) => {
                            if (!isNaN(e)) {
                              return e;
                            }
                          }
                        })(<Input
                          style={{ width: '160px' }}
                          placeholder={'请输入序号'}
                          onChange={(e) => { saveSort(e.target.value, i) }}
                        />)}
                      </FormItem>
                    </div>
                  </div>
                  <div className={styles.oBannerRight}>
                    <Button className={styles.oBannerRightBtn} onClick={() => { changeUrl({ oVisible: true }, i) }}>
                      {item.href ? '更改' : '添加'}链接
                    </Button>
                    <Popconfirm placement="top" title={"确定删除当前广告轮播图吗？"} onConfirm={() => delImg(i)} okText="确定" cancelText="取消">
                      <Button>删除</Button>
                    </Popconfirm>
                    <Button type="primary" style={{ marginTop: '15px' }} onClick={() => { saveBanner(i) }}>保存</Button>
                  </div>
                </div>
              </Col>
            })
          }
        </Row>
        }
        {/*大B*/}
        {channelIndex==2&&
        <Row gutter={16} className={styles.oBanners} >
          {
            bannerList['2'] && bannerList['2'].map((item, i) => {
              return <Col span={12} key={'otoBanners_' + i} className={styles.largeBanners}>
                <div className={styles.largeBanner}>
                  <div className={styles.oBannerLeft}>
                    图{i + 1}
                  </div>
                  <div className={styles.oBannerMiddle}>
                    <Uploader uploadedUrls={item.url}
                              // imgUrlSize={'146'}
                              removeFileCbf={(e) => { removeImgUrl(i) }}
                              uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl, i) }}
                              showType={'3'}
                              fileType='image'
                              fileMaxSize='0.3'
                              minCropBoxWidth={1372}
                              minCropBoxHeight={736}
                              maxFiles='1' />
                    <div>
                      <Tooltip placement="topLeft" title="链接地址：（链接请加上传输协议，如http://或https://）">
                        <div style={{ textIndent: '24px', margin: '10px 0' }}>链接地址：(链接请加上传输协议，如http://或https://)</div>
                      </Tooltip>
                      <div className={styles.oImgUrls}>
                        <p className={styles.urlCss}>
                          {item.href ? item.href : '暂无链接...'}
                        </p>
                      </div>
                      <FormItem {...formItemLayout} label="序号" required={true}>
                        {getFieldDecorator(`ord${i}`, {
                          initialValue: item.ord,
                          normalize: (e) => {
                            if (!isNaN(e)) {
                              return e;
                            }
                          }
                        })(<Input
                          style={{ width: '160px' }}
                          placeholder={'请输入序号'}
                          onChange={(e) => { saveSort(e.target.value, i) }}
                        />)}
                      </FormItem>
                    </div>
                  </div>
                  <div className={styles.oBannerRight}>
                    <Button className={styles.oBannerRightBtn} onClick={() => { changeUrl({ oVisible: true }, i) }}>
                      {item.href ? '更改' : '添加'}链接
                    </Button>
                    <Popconfirm placement="top" title={"确定删除当前广告轮播图吗？"} onConfirm={() => delImg(i)} okText="确定" cancelText="取消">
                      <Button>删除</Button>
                    </Popconfirm>
                    <Button type="primary" style={{ marginTop: '15px' }} onClick={() => { saveBanner(i) }}>保存</Button>
                  </div>
                </div>
              </Col>
            })
          }
        </Row>
        }

      </CollapsiblePanels>
      <Pagination onChange={onChange} style={{ textAlign: 'right', marginTop: '-15px', background: '#fff', padding: '16px' }} total={Number(pageInfo[channelIndex]['total']||0)} showSizeChanger showQuickJumper />
      {/*链接弹窗*/}
       <Modal
        visible={oVisible}
        onOk={oHandleOk}
        onCancel={() => { changeState({ oVisible: false }) }}
        width={'888px'}
      >
        <div style={{ padding: '10px' }}>
          <div className={'mgb1'}>广告链接</div>
          <Form>
{/*            <FormItem {...formItemLayout} label="跳转链接" hasFeedback>
              {getFieldDecorator('writeUrl', {
                initialValue: writeUrl,
                // rules: [
                //   { required: true, whitespace: true, message: `请输入正确链接`, pattern: /(http|ftp|https):\/\/([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ },
                // ],
              })(<Input
                placeholder={'请输入链接'}
                onChange={(e) => { saveUrl(e) }}
              />)}
            </FormItem>*/}
            <Tabs onChange={(activeKey)=>{changeState({activeKey})}} type="card" activeKey={activeKey}>
              {/*<TabPane tab="小程序路径" key="1">*/}
                {/*<div className={styles.comLeftTre}>*/}
                  {/*/!*品类配置*!/*/}
                  {/*<div>*/}
                    {/*<Row>*/}
                      {/*<Col span={12}>*/}
                        {/*<div className={styles.cateCss}>*/}
                          {/*<Tree*/}
                            {/*onExpand={onExpand}*/}
                            {/*onSelect={onSelect}*/}
                            {/*expandedKeys={mpUrlsObj.expandedKeys}*/}
                            {/*autoExpandParent={mpUrlsObj.autoExpandParent}*/}
                            {/*selectedKeys={mpUrlsObj.selectedKeys}*/}
                          {/*>*/}
                            {/*{loop(mpUrlsObj.mpUrls)}*/}
                          {/*</Tree>*/}
                        {/*</div>*/}
                      {/*</Col>*/}
                      {/*<Col span={12}>*/}
                        {/*<FormItem {...formItemLayout} label="跳转链接" hasFeedback>*/}
                          {/*{getFieldDecorator('currentItem', {*/}
                            {/*initialValue: mpUrlsObj.currentItem.key,*/}
                            {/*// rules: [*/}
                            {/*//   { required: true, whitespace: true, message: `请输入正确链接`, pattern: /(http|ftp|https):\/\/([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ },*/}
                            {/*// ],*/}
                          {/*})(<Input*/}
                            {/*placeholder={'请输入链接'}*/}
                            {/*onChange={(e) => {*/}
                              {/*mpUrlsObj.currentItem.key=e.target.value;changeState({mpUrlsObj})*/}
                            {/*}}*/}
                          {/*/>)}*/}
                        {/*</FormItem>*/}
                      {/*</Col>*/}
                    {/*</Row>*/}
                  {/*</div>*/}
              
                  {/*{*/}
                    {/*mpUrlsObj.mpUrls <= 0 &&(*/}
                      {/*<div style={{color:'#ccc', textAlign:'center'}}>*/}
                        {/*暂无目录...*/}
                      {/*</div>*/}
                    {/*)*/}
                  {/*}*/}
                {/*</div>*/}
              {/*</TabPane>*/}
              <TabPane tab="外部链接" key="2">
                <FormItem {...formItemLayout} label="跳转链接" hasFeedback>
                  {getFieldDecorator('writeUrl', {
                    initialValue: writeUrl,
                    // rules: [
                    //   { required: true, whitespace: true, message: `请输入正确链接`, pattern: /(http|ftp|https):\/\/([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ },
                    // ],
                  })(<Input
                    placeholder={'请输入链接'}
                    onChange={(e) => { saveUrl(e) }}
                  />)}
                </FormItem>
              </TabPane>
            </Tabs>
          </Form>
        </div>
      </Modal>
      <Modal
        visible={newBanner}
        onOk={newBanenrOk}
        onCancel={() => { changeState({ newBanner: false }) }}
        width={'888px'}
      >
        <div style={{ padding: '10px' }}>
          <div style={{ fontSize: '16px', marginBottom: '24px' }}>新增广告图</div>
          <Row gutter={16} className={styles.oBanners}>
            {
              newBannerList && newBannerList.map((item, i) => {
                return <Col span={12} key={'otoBanners_' + i} className={styles.largeBanners}>
                  <div className={styles.largeBanner} style={{ minWidth: '700px' }}>
                    <div className={styles.oBannerLeft}>
                      图{i + 1}
                    </div>
                    <div className={styles.oBannerMiddle}>
                      <Uploader uploadedUrls={item.url}
                                // imgUrlSize={'146'}
                                previewVisible={true}
                                removeFileCbf={(e) => { removenewImgUrl(i) }}
                                uploadSuccessCbf={(imgUrl) => { updatenewImageModel(imgUrl, i) }}
                                showType={'3'}
                                fileType='image'
                                fileMaxSize='0.3'
                                minCropBoxWidth={1372}
                                minCropBoxHeight={736}
                                maxFiles='1' />
                      <div>
                        <Tooltip placement="topLeft" title="链接地址：（链接请加上传输协议，如http://或https://）">
                          <div style={{ margin: '10px 0' }}>链接地址：(链接请加上传输协议，如http://或https://)</div>
                        </Tooltip>
                        <div style={{ margin: '16px 0' }} className={styles.oImgUrls}>
                          <p className={styles.urlCss}>
                            {item.href ? item.href : '暂无链接...'}
                          </p>
                        </div>
                        {newBanner && !oVisible ? <FormItem {...formItemLayout} label="序号">
                          {getFieldDecorator('ord', {
                            initialValue: item.ord,
                            rules: [
                              { required: true, whitespace: true, message: '请输入序号' },
                            ],
                            normalize: (e) => {
                              if (!isNaN(e)) {
                                return e;
                              }
                            }
                          })(<Input
                            style={{ width: '160px' }}
                            placeholder={'请输入序号'}
                            onChange={(e) => { saveSortNew(e.target.value) }}
                          />)}
                        </FormItem> : null}
                      </div>
                    </div>
                    <div className={styles.oBannerRight}>
                      <Button className={styles.oBannerRightBtn} onClick={() => { changeUrl({ oVisible: true }, i, 'new') }}>
                        {item.href ? '更改' : '添加'}链接
                      </Button>
                    </div>
                  </div>
                </Col>
              })
            }
          </Row>
        </div>
      </Modal>
    </Form>

  </div>
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
